package com.example.springboot_demo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.springboot_demo.bean.User;
import com.example.springboot_demo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
public class TestServiveImpl implements TestService {
    @Autowired
    DataSource dataSource;
    @Override
    public Object queryOne() throws SQLException {
        //原生JDBC操作 sql
        Connection connection = dataSource.getConnection();
        // statement 是和数据库 打交道的
        Statement statement = connection.createStatement();
        String sql = "select * from tz_user";
        ResultSet resultSet = statement.executeQuery(sql);

        ResultSetMetaData metaData = resultSet.getMetaData();
        int count = metaData.getColumnCount();
        ArrayList<Map<String, Object>> list_map = new ArrayList<>();
        while (resultSet.next()) {
            Map<String, Object> map = new HashMap<>();
            for(int i = 0; i < count; i++) {
                String name = metaData.getColumnLabel(i + 1); // 第一个 是 1 第二个 是2
                String val = resultSet.getString(name);
                map.put(name, val);
                list_map.add(map);
            }
        }
        Object o = JSONObject.toJSON(list_map);
        connection.close();

        return o;
    }
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Override
    public boolean addUser(User user) {
        // 使用springboot 自带的 jDBCTmplate 操作数据库
        String sql = "insert into tz_user(id,tzxm,tzdh,tzjb,xzqdm,create_time, update_time) " +
                "values ('"+ user.getId() +"',' "+ user.getTzxm() +"','"+ user.getTzdh() +"', '"+ user.getTzjb() +"', '"+ user.getXzqdm() +"', '"+user.getCreateTime()+"',' "+ user.getUpdateTime() +"');";
//        Object[] objects = new Object[7];
//        objects[0] = user.getId();
//        objects[1] = user.getTzxm();
//        objects[2] = user.getTzdh();
//        objects[3] = user.getTzjb();
//        objects[4] = user.getXzqdm();
//        objects[5] = user.getCreateTime();
//        objects[6] = user.getUpdateTime();
        System.out.println(sql);
        int update = jdbcTemplate.update(sql);
//        int update =0;

        return update >= 1 ? true : false;
    }
}
